(function () {
var cache = {},
	source = new XMLHttpRequest(),
	xhr = new XMLHttpRequest(),
	defaultValidator = "http://validator.w3.org/check";

chrome.extension.onRequest.addListener(function (request, sender, response) {
	var validator = localStorage["validator"] || defaultValidator,
		hosts = localStorage["validateHosts"] || "";

		hosts = hosts.split(" ");

	if (request["action"] === "init") {
		chrome.pageAction.show(sender.tab.id);
		chrome.pageAction.onClicked.addListener(function () {
			validate(request, sender, response);
		});
		if (arrayContains(hosts, request["host"])) {
			validate(request, sender, response);
		}
	}
	else if (request["action"] === "validate") {
		validate(request, sender, response);
	}
});

function validate (request, sender, response) {
	var validator = localStorage["validator"] || defaultValidator,
		url = sender.tab.url,
		tabId = sender.tab.id,
		useCache = request["useCache"] || false;

	//	Create an object to cache results for the current tab
	if (cache[sender.tab.url] === undefined) {
		cache[sender.tab.url] = {};
	}

	xhr.onreadystatechange = function () {
		processResult(tabId, url, sender);
	};

	source.onreadystatechange = function () {
		var docSource;
		if (source.readyState === 4) {
			if (source.status === 200) {
				docSource = source.responseText;
				if (useCache && [url]["source"] == docSource) {
					//	Use cached data
					console.info("Cached result");
					setResult(tabId, cache[url]["errorCount"]);
				} else {
					//	Send request to validator
					console.info("Validator result");
					cache[url]["source"] = docSource;
					xhr.open("GET", validator + "?output=soap12&amp;url=" + escape(url), true);
					/*xhr.setRequestHeader("output", "soap12");
					xhr.setRequestHeader("fragment", docSource);*/
					xhr.send();
					chrome.pageAction.setTitle({
						"tabId": tabId,
						"title": "Waiting for validator..."
					});
					chrome.pageAction.setIcon({
						"tabId": tabId,
						"path": "img/connect.png"
					});
				}
			}
			else {
				//	Error
				chrome.pageAction.setTitle({
					"tabId": tabId,
					"title": "Error: " + source.statusText
				});
				chrome.pageAction.setIcon({
					"tabId": tabId,
					"path": "img/html_delete.png"
				});
			}
		}
	}

	source.open("GET", sender.tab.url);
	source.send();
}

function processResult (tabId, url, sender) {
	if (xhr.readyState === 4) {
		if (xhr.status === 200) {
			var errorCount;
	
			if (xhr.responseXML.getElementsByTagName("errorcount")) {
				errorCount = parseInt(xhr.responseXML.getElementsByTagName("errorcount")[0].textContent);
			}
	
			console.info(errorCount);
	
			//	Cache results
			//cache[url]["url"] = url;
			cache[url]["errorCount"] = errorCount;
	
			setResult(tabId, errorCount, sender);
		}
		else {
			//	Error
			chrome.pageAction.setTitle({
				"tabId": tabId,
				"title": "Error: " + xhr.statusText
			});
			chrome.pageAction.setIcon({
				"tabId": tabId,
				"path": "img/html_delete.png"
			});
		}
	}
}

function setResult (tabId, errorCount, sender) {
	if (errorCount === 0) {
		chrome.pageAction.setIcon({
			"tabId": tabId,
			"path": "img/accept.png"
		});
		chrome.pageAction.setTitle({
			"tabId": tabId,
			"title": "Page is valid"
		});
	}
	else {
		chrome.pageAction.setIcon({
			"tabId": tabId,
			"path": "img/exclamation.png"
		});
		chrome.pageAction.setTitle({
			"tabId": tabId,
			"title": errorCount + " validation errors"
		});
	}
	//	Open validator in new tab
	chrome.pageAction.onClicked.removeListener();
	chrome.pageAction.onClicked.addListener(function () {
		var validator = localStorage["validator"] || defaultValidator;
		openValidatorTab(validator, sender.tab.url);
	});
}

function openValidatorTab (validator, url) {
	chrome.tabs.create({
		"url": validator + "?url=" + escape(url),
		"selected": true
	});
}

function arrayContains (arr, value) {
	for (var i = 0; i <= arr.length; i++) {
		console.info(arr[i]);
		console.info(value);
		if (arr[i] === value) {
			return true;
		}
		return false;
	}
}
})();